<?php


namespace App\Services;

use App\Models\Module;
use App\Models\NewRoles;
use Illuminate\Support\Facades\DB;
use Illuminate\Http\Request;

class ModuleService
{
    private const STATUS_ENABLE = 1;

    /**
     * 增加模块
     *
     * @param Request $request
     * @param int $role_id
     * @return bool
     */
    public function addModule(Request $request, int $role_id): bool
    {
        if (empty($request->input('module_ids'))) {
            return true;
        }

        DB::beginTransaction();
        DB::table("xpel_role_module")->where('role_id', $role_id)->delete();
        foreach ($request->get('module_ids') as $item) {
            if (strpos($item, '-') !== false) {
                $item = explode('-', $item);
                $menu_id = $item[1];
                $module_id = $item[0];
            } else {
                $module_id = $item;
                $menu_id = 0;
            }

            $insertData = DB::table("xpel_role_module")->insert([
                'role_id' => $role_id,
                'module_id' => $module_id,
                'menu_id'   => $menu_id,
                'status'    => self::STATUS_ENABLE,
            ]);

            if (!$insertData) {
                DB::rollBack();
                throw new Exception('操作失败');
            }
        }

        DB::commit();
        return true;
    }

    /**
     * 获取所有的module
     *
     * @return array
     */
    public function getModules(): array
    {
        $modules = DB::table('xpel_module as module')
            ->select('module.*',
                'menu.status as menu_status',
                'menu.simple_chinese_name as menu_simple_chinese_name',
                'menu.traditional_chinese_name as menu_traditional_chinese_name',
                'menu.english_name as menu_english_name',
                'menu.name as menu_name',
                'menu.id as menu_id',
                'menu.module_id as menu_module_id'
            )
            ->leftJoin('xpel_menu as menu', 'module.id', 'menu.module_id')
            ->where('module.status', self::STATUS_ENABLE)
            ->orderBy('module.sort', 'asc')
            ->get();

        $data = [];
        if (!empty($modules)) {
            $parentModuleIdArr = [];
            foreach ($modules as $module) {
                $moduleIdArr = [];
                if ($module->parent_id === 0 && !in_array($module->id, $parentModuleIdArr)) {
                    $value = $module;
                    $moduleIdArr[] = $module->id;
                    $parentModuleIdArr[] = $module->id;
                    foreach ($modules as $item) {
                        if ($item->parent_id === $module->id && !in_array($item->id, $moduleIdArr)) {
                            $value->sub_modules[] = $item;
                            $moduleIdArr[] = $item->id;
                        }
                    }
                    if (!empty($moduleIdArr)) {
                        foreach ($modules as $item) {
                            if (!empty($item->menu_name) && in_array($item->menu_module_id, $moduleIdArr)) {
                                $value->menus[] = $item;
                            }
                        }
                    }
                    $data[] = $value;
                }
            }
        }

        return $data;
    }

    public function getRoleMenu(int $role_id)
    {
        $modules = DB::table('xpel_role_module')
            ->leftJoin('xpel_module', 'xpel_module.id', 'xpel_role_module.module_id')
            ->where('xpel_role_module.role_id', $role_id)
            ->orderBy('sort')
            ->get();
        $menu = [];

        if (empty($modules)) {
            return $menu;
        }

        $parentModuleIdArr = [];
        foreach ($modules as $module) {
            if ($module->parent_id === 0 && !in_array($module->id, $parentModuleIdArr)) {
                $data = [
                    'icon' => $module->icon,
                    'text' => $module->simple_chinese_name,
                    'url'  => $module->url ? $module->url : '#',
                    'page_name' => $module->page_name ? explode(",", $module->page_name) : [''],
                ];
                $parentModuleIdArr[] = $module->id;
                $moduleArr = [];
                foreach ($modules as $item) {
                    if ($item->parent_id === $module->id && !in_array($item->id, $moduleArr)) {
                        $data['sub'][] = [
                            'text' => $item->simple_chinese_name,
                            'url' => $item->url ? $item->url : '#',
                            'page_name' => $item->page_name ? explode(",", $item->page_name) : [''],
                        ];
                        $moduleArr[] = $item->id;
                    }
                }
                $menu[] = $data;
            }
        }

        return $menu;
    }

    /**
     * 获取页面上的按钮
     *
     * @param int $roleId
     * @param string $url
     * @return array|mixed
     */
    public function getWebButton(int $roleId, string $url)
    {
        $module = DB::table('xpel_module')->where('url', '/' . $url)->first();
        if (empty($module)) {
            return [];
        }
        //dd($module->id, $roleId);
        $result = DB::table('xpel_role_module')
            ->where('role_id', $roleId)
            ->where('module_id', $module->id)
            ->where('status', self::STATUS_ENABLE)
            ->get();
        $menuIdArr = [];
        if (empty($result)) {
            return [];
        }

        foreach ($result as $item) {
            $menuIdArr[] = $item->menu_id;
        }

        $menus = DB::table('xpel_menu')->whereIn('id', $menuIdArr)->get();

        if (empty($menus)) {
            return [];
        }

        $data = [];
        foreach ($menus as $menu) {
            $data[] = $menu->name;
        }
        return array_unique($data);
    }
}